import 'package:dio/dio.dart';

import '../http/dio_http_instance.dart';
import '../http/rest_api_base_model.dart';
import 'models/auth_model.dart';

class ApiAuthCenter {
  static const String serverName = "auth-center";

  ApiAuthCenter._();

  static ApiAuthCenter api = ApiAuthCenter._();

  /// 获取密码加密公钥
  Future<PublicKeyResponse?> getPublicKey() async {
    Response response = await DioFactory.getInstance(serverName)
        .get("/api/auth/sm2/publicKey?action=passwordEncrypt");

    final gRsp = GeneralResponse<PublicKeyResponse>.fromJson(
        response.data, (json) => PublicKeyResponse.fromJson(json));

    return gRsp.data;
  }

  /// 登录
  Future<AuthLoginResponse?> login(Map<String, dynamic> map) async {
    var response = await DioFactory.getInstance(serverName)
        .post("/api/auth/login", data: map);

    final gRsp = GeneralResponse<AuthLoginResponse>.fromJson(
        response.data, (json) => AuthLoginResponse.fromJson(json));

    return gRsp.data;
  }

  /// 退出登录
  Future<bool?> logout(String gsid) async {
    Map<String, dynamic>? params = {"gsid": gsid};
    var response = await DioFactory.getInstance(serverName)
        .post("/api/auth/logout", queryParameters: params);

    final gRsp =
        GeneralResponse<bool>.fromJson(response.data, (json) => (json));

    if (gRsp.data is bool) {
      return gRsp.data;
    }
    return false;
  }

  /// 获取用户信息
  Future<AuthMeResponse?> me() async {
    var response = await DioFactory.getInstance(serverName).get("/api/auth/me");

    final gRsp = GeneralResponse<AuthMeResponse>.fromJson(
        response.data, (json) => AuthMeResponse.fromJson(json));

    return gRsp.data;
  }

  /// refresh token
  Future<AuthTokenResponse?> refreshToken(String rft) async {
    const path = "/api/auth/refreshToken";
    final body = {"refreshToken": rft};
    var response =
        await DioFactory.getInstance(serverName).post(path, data: body);

    final gRsp = GeneralResponse<AuthTokenResponse>.fromJson(
        response.data, (json) => AuthTokenResponse.fromJson(json));

    return gRsp.data;
  }
}
